import random
import time
import cv2
import numpy as np
import pydirectinput
import judgment


def auto_click(var_centre):
    """
    接收一个元组，并进行点击
    :param var_centre: 坐标元组
    :return: NONE
    """
    type =  random.randint(0, 1)
    if type == 0:
        pydirectinput.click(var_centre[0], var_centre[1])
        print('单点', var_centre)
        out_time = random.randint(0, 5)
        time.sleep(out_time)
    elif type == 1:
        pydirectinput.doubleClick(var_centre[0], var_centre[1])
        print('双击', var_centre)
        out_time = random.randint(0, 5)
        time.sleep(out_time)

def get_xy(img_target, result):
    """
    获取屏幕截图
    :return: 目标坐标
    """
    # 读取模板横宽
    width, height, channel = np.shape(img_target)
    #1/4的模板横款
    if height % 2 == 0:
        height2 = int(height / 4)
    else:
        height2 = int((height - 1) / 4)

    if width % 2 == 0:
        width2 = int(width / 4)
    else:
        width2 = int((width - 1) / 4)
    # 解析出匹配区域的左上角
    update_left = cv2.minMaxLoc(result)[2]
    # 计算匹配区域的右下角的坐标
    lower_right = (update_left[0] + width, update_left[1] + height)
    #设置高度随机数
    random_height = random.randint(-height2, height2)
    #设置宽度随机数
    random_width = random.randint(-width2, width2)
    # 中心点为主的随机点数
    random_centre = (int(((update_left[0] + lower_right[0]) / 2) + random_width),
                    int(((update_left[1] + lower_right[1]) / 2) + random_height))
    key = cv2.waitKey(0)
    if (key == 'q'):
        exit()
    cv2.destroyAllWindows()
    return random_centre

def main():
    Serial_Nonum = 0
    while True:
        # 判断执行内容
        length = judgment.judgment(Serial_Nonum)[0]
        if length != 0:
            """
            img：全屏截图
            img_target：目标截图
            result：归一化返回值
            similar：最小值
            Serial_Nonum：执行序号
            """
            length2 = judgment.judgment(length)[0]
            if length2 != 0:
                Serial_Nonum, img, img_target, result, similar = judgment.judgment(length)
                centre = get_xy(img_target, result)
                auto_click(centre)

main()